<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" size="large" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 200px">
          <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="预计验收日期" style="width: 308px">
        <el-date-picker v-model="daterangeAcceptTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="立项金额">
        <div style="display: flex; align-items: center;">
          <el-input v-model="queryParams.minProjectAmount" placeholder="最小金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-right: 10px;" />
          -
          <el-input v-model="queryParams.maxProjectAmount" placeholder="最大金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-left: 10px;" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>

        <!-- <el-button type="primary" icon="Search" @click="handleSync">同步数据</el-button> -->
      </el-form-item>
    </el-form>
    <right-toolbar v-model:showSearch="showSearch"></right-toolbar>
    <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
      <el-checkbox-group v-model="selectedProps">
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
          {{ col.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
    </div>
    <el-table v-loading="loading" :data="projectList" border>
      <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
        :align="'center'"
        :show-overflow-tooltip="['contractAmount', 'settlementAmount', 'housekeeperName'].includes(col.prop)"
        :width="getWidth(col.prop)">
        <!-- 特殊列的插槽处理 -->
        <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
          <span>{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 固定操作列 -->
      <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 80 : 220" align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改绩效基本信息对话框 -->
    <el-dialog fullscreen v-model="open" width="800px" append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
          <projectView :key="'projectView' + form.projectNo" :datas="form" :column="3" :sizes="'large'"></projectView>

          <div style="margin-top: 20px;">
            <!-- 第一行：4个卡片 -->
            <el-row :class="{ 'mobile-row': userStore.isMobile }" style="justify-content: space-around;">
              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
                  <span>
                    项目发起时间:
                    <el-tag type="primary">
                      {{ resultData.project?.createTime }}
                    </el-tag>
                  </span>
                  <span style="padding-top: 10px;">
                    距今共:
                    <el-tag type="primary">{{ resultData?.days }}</el-tag>天
                  </span>
                </div>
              </el-card>

              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
                  <span style="padding-top: 10px;">
                    合同金额￥
                    <el-tag type="primary">
                      {{ resultData.project.contractAmount }}
                    </el-tag>
                    元
                  </span>
                  <span style="padding-top: 10px;">
                    结算金额￥:
                    <el-tag type="primary">
                      {{ resultData.project.settlementAmount }}
                    </el-tag>元
                  </span>
                </div>
              </el-card>

              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
                  <span style="padding-top: 10px;">
                    项目成本
                    <el-tag type="primary">
                      {{ resultData.cost }}
                    </el-tag>
                    元
                  </span>
                  <span style="padding-top: 10px;">
                    毛利润￥:
                    <el-tag type="primary">
                      {{ resultData.profit }}
                    </el-tag>元
                  </span>
                </div>
              </el-card>

              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
                  <span style="padding-top: 10px;">
                    项目成本税费￥：
                    <el-tag type="primary">
                      {{ resultData.costFees }}
                    </el-tag>
                    元
                  </span>
                  <span style="padding-top: 10px;">
                    差额税费￥:
                    <el-tag type="primary">
                      {{ resultData.differenceFees }}
                    </el-tag>元
                  </span>
                </div>
              </el-card>
            </el-row>

            <!-- 第二行：4个卡片 -->
            <el-row :class="{ 'mobile-row': userStore.isMobile }"
              style="justify-content: space-around;margin-top: 20px;">
              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
                  <span style="padding-top: 10px;">
                    税前利润￥
                    <el-tag type="primary">
                      {{ resultData.beforeProfit }}
                    </el-tag>
                    元
                  </span>
                  <span style="padding-top: 10px;">
                    纯利润扣质保金￥:
                    <el-tag type="primary">
                      {{ resultData.afterProfit }}
                    </el-tag>元
                  </span>
                </div>
              </el-card>

              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
                  <span style="padding-top: 10px;">
                    项目税额￥
                    <el-tag type="primary">
                      {{ resultData.taxAmount }}
                    </el-tag>
                    元
                  </span>
                  <span style="padding-top: 10px;">
                    累计收款￥
                    <el-tag type="primary">
                      {{ resultData.receiveAmount }}
                    </el-tag>
                    元
                  </span>
                </div>
              </el-card>

              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
                  <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px;">
                    <span>
                      项目共有：
                      <el-tag type="primary">
                        {{ resultData.participanList.length }}
                      </el-tag>
                      人参与
                    </span>
                    <el-icon style="cursor: pointer;" @click="openDrawer(resultData.participanList, 'participanList')">
                      <ArrowRight />
                    </el-icon>
                  </span>
                  <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px;">
                    <span>
                      附件共：
                      <el-tag type="primary">
                        {{ resultData.fileList.length }}
                      </el-tag>
                      个
                    </span>
                    <el-icon style="cursor: pointer;" @click="openDrawer(resultData.fileList, 'attachmentList')">
                      <ArrowRight />
                    </el-icon>
                  </span>
                </div>
              </el-card>

              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
                  <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px;">
                    <span>
                      收款信息共有：
                      <el-tag type="primary">
                        {{ resultData.payList.length }}
                      </el-tag>
                      条
                    </span>
                    <el-icon style="cursor: pointer;" @click="openDrawer(resultData.payList, 'payList')">
                      <ArrowRight />
                    </el-icon>
                  </span>
                  <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px;">
                    <span>
                      实施日志共：
                      <el-tag type="primary">
                        {{ resultData.implementList.length }}
                      </el-tag>
                      条
                    </span>
                    <el-icon style="cursor: pointer;" @click="openDrawer(resultData.implementList, 'implementList')">
                      <ArrowRight />
                    </el-icon>
                  </span>
                </div>
              </el-card>
            </el-row>

            <!-- 第三行：2个卡片 -->
            <el-row :class="{ 'mobile-row': userStore.isMobile }"
              style="justify-content: start;margin-top: 20px;margin-left: 2.2vw;">
              <el-card style="width: 20vw;">
                <div
                  style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
                  <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px;">
                    <span>
                      核算信息共有：
                      <el-tag type="primary">
                        {{ resultData.accountingList.length }}
                      </el-tag>
                      条
                    </span>
                    <el-icon style="cursor: pointer;" @click="openDrawer(resultData.accountingList, 'accountingList')">
                      <ArrowRight />
                    </el-icon>
                  </span>
                  <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px;">
                    <span>
                      质保信息共有：
                      <el-tag type="primary">
                        {{ resultData.warrantyList.length }}
                      </el-tag>
                      条
                    </span>
                    <el-icon style="cursor: pointer;" @click="openDrawer(resultData.warrantyList, 'warrantyList')">
                      <ArrowRight />
                    </el-icon>
                  </span>
                </div>
              </el-card>

              <el-card style="width: 20vw;margin-left: 4vw;">
                <div
                  style="display: flex; flex-direction: column;font-size: 14px;color: var(--el-text-color-regular);font-weight: bold;">
                  <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px;">
                    <span>
                      共：
                      <el-tag type="primary">
                        {{ resultData.allocationPerson }}
                      </el-tag>
                      人参与绩效分配
                    </span>
                    <el-icon style="cursor: pointer;" @click="openAllocationDrawer()">
                      <ArrowRight />
                    </el-icon>
                  </span>
                </div>
              </el-card>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>

        <el-tab-pane label="配套施工清单" name="seven">
          <matching v-if="activeName == 'seven'" :datas="form"></matching>
        </el-tab-pane>

      </el-tabs>
      <!-- 是否有 超级管理员 项目经理 销售 销售负责人 商务 财务权限之一  -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
          <el-button type="primary" @click="rollBack">回退环节</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" @open="handleDrawerOpen" direction="ttb" :with-header="false">
      <projectViewItem :datas="form" :isView="true" ref="itemViewRef"></projectViewItem>
    </el-drawer>

    <el-drawer v-model="allocationDrawer" direction="ttb" size="50%" :with-header="false">
      <allocation ref="allocationRef"></allocation>
    </el-drawer>


    <!-- 查看 -->
    <el-dialog v-model="openView" fullscreen append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
          <!-- <projectView :datas="form" :isView="isView" :column="3" :sizes="'large'" :personList="personList"
        :attachmentList="attachmentList" :payList="payList"  :warrantyList="warrantyList" :implementList="implementList" :accountingList="accountingList"></projectView>
     -->

          <projectView :key="'projectView' + form.projectNo" :datas="form" :isView="isView" :column="3"
            :sizes="'large'">
          </projectView>

        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>

        <el-tab-pane label="配套施工清单" name="seven">
          <matching v-if="activeName == 'seven'" :datas="form"></matching>
        </el-tab-pane>

      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>


    </el-dialog>



    <!-- 环节回退 -->
    <el-dialog title="回退到上一个环节" v-model="openRollBack" width="600px" append-to-body>
      <el-form :model="form" label-width="80px">

        <el-form-item label="留言" prop="remark">
          <el-input v-model="form.phaseRemark" type="textarea" placeholder="请输入留言" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRollBack">确 定</el-button>
          <el-button @click="cancelRollBack">取 消</el-button>
        </div>
      </template>、
    </el-dialog>


  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  syncData,
  getCompanyList,
  getFinanceList,
  listParticipan, getParticipan, delParticipan, addParticipan, updateParticipan, getPermission,
  getStatus, listImplement, getResults, saveUserTableConfig, getUserTableConfig
} from "@/api/project/project";
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment, rollBackPhase } from "@/api/project/project";
import {
  listPay, getTotalCost, listWarranty, getWarranty, delWarranty, addWarranty, updateWarranty,
  getPay, delPay, addPay, updatePay, listPhase, getPhase, delPhase, addPhase, updatePhase, listAccounting, getAccounting, delAccounting, addAccounting, updateAccounting
} from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import {
  ArrowRight,
  CaretBottom,
  CaretTop,
  Warning,
} from '@element-plus/icons-vue'
import allocation from "../allocation.vue";
import { listDictionary } from "@/api/project/dictionary.js";
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();

const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { profit_type } = proxy.useDict('profit_type');
const { rate_type } = proxy.useDict('rate_type');
const { warranty_rate } = proxy.useDict('warranty_rate');
const attachmentList = ref([]);
const payList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const companyList = ref([]);
const financeList = ref([]);
const accountingList = ref([]);
const implementList = ref([]);
const logs = ref([]);
const warrantyList = ref([]);
const open = ref(false);
const openView = ref(false);
const isView = ref(false);
const openOper = ref(false);
const openPhase = ref(false);
const openFile = ref(false);
const openWarranty = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const fileAccept = ref(["doc", "docx", "cad", "dwg", "xls", "ppt", "txt", "pdf", "xlsx", 'png', 'jpg', 'jpeg'],);
const projectNo = ref("")
const contractAmount = ref(0)
const settlementAmount = ref(0)
const materialCost = ref(0)
const companyId = ref('')
const company = ref('')
const finance = ref(false);//当期人员是否是财务
const isAdmin = ref(false);//是否是超级管理员
const havePay = ref(false);//是否有添加付款信息的权限
const status = ref("0");
const currenrPhaseId = ref()
const phasetList = ref([]);
const formDisabled = ref(true);
const itemViewRef = ref(null)
let currentPhase = reactive({
  phaseCode: '',
});
const allocationRef = ref()
const resultData = ref({
  personList: [],
  attachmentList: [],
  payList: [],
  accountingList: [],
  implementList: [],
  warrantyList: [],
  project: {
    acceptTime: null,
    approvalDate: null,
    contractAmount: null,
    createBy: null,
    createDept: null,
    createDeptName: null,
    createTime: null,
    createUserId: null,
    createUserName: null,
    customerAddress: null,
    customerName: null,
    delFlag: null,
    deptId: null,
    housekeeperName: null,
    housekeeperProject: null,
    joinPeople: null,
    loginDate: null,
    loginIp: null,
    message: null,
    participanList: null,
    phaseId: null,
    phaseName: null,
    planDate: null,
    projectAmount: null,
    projectName: null,
    projectNo: null,
    projectType: null,
    projectTypeName: null,
    projectUnit: null,
    remark: null,
    settlementAmount: null,
    startDate: null,
    updateBy: null,
    updateTime: null,
    userId: null,
  }
})

import projectView from "../projectView.vue";

import projectViewItem from "../projectViewItem.vue";
import { nextTick, ref } from "vue";
import { pa } from "element-plus/es/locale/index.mjs";
import { getToken } from "@/utils/auth";
import Hls from "hls.js";
const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  personForm: {
  },
  fileForm: {

  },
  warrantyForm: {

  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: 1,//写死 查询上个阶段已完成的项目 1是进行中 2是已完成 
    // 新建项目的时候会默认插入一条立项阶段到立项表 点击下一步的时候会更新阶段表把当前项目当前阶段的状态
    //改为已完成  同时往阶段表插入下一个阶段 状态是1 进行中
    phaseId: 7,//阶段字典id 查询已归档
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },

});

const drawer = ref(false)
const allocationDrawer = ref(false)
const drawerTime = ref(false)
const isSales = ref(false)
const types = ref()
const currentItem = ref([])

const handleDrawerOpen = () => {
  const item = currentItem.value; // 根据你的逻辑获取 item
  const type = types.value // 获取当前打开的类型

  if (itemViewRef.value) {
    itemViewRef.value.initData(item, type);
  }
};

function openDrawer(item, type) {
  types.value = type
  currentItem.value = item
  console.log("openDrawer", item);

  // 根据需要重新赋值
  if (type == 'participanList') {
    resultData.value.personList = item

    //   nextTick(() => {
    //   if (itemViewRef.value) {
    //     itemViewRef.value.initData(item,type); // 调用子组件方法
    //   } else {
    //   }
    // });

  } else if (type == 'attachmentList') {
    resultData.value.attachmentList = item

    //   nextTick(() => {
    //   if (itemViewRef.value) {
    //     itemViewRef.value.initData(item,type); // 调用子组件方法
    //   }
    // });

  } else if (type == 'payList') {
    resultData.value.payList = item

    //   nextTick(() => {
    //   if (itemViewRef.value) {
    //     itemViewRef.value.initData(item,type); // 调用子组件方法
    //   }
    // });

  } else if (type == 'accountingList') {

    if (!isSales.value) {
      proxy.$modal.msgError("暂无权限查看");
      return
    }

    resultData.accountingList = item
    //   nextTick(() => {
    //   if (itemViewRef.value) {
    //     itemViewRef.value.initData(item,type); // 调用子组件方法
    //   }
    // });
  } else if (type == 'implementList') {
    resultData.value.implementList = item
    //   nextTick(() => {
    //   if (itemViewRef.value) {
    //     itemViewRef.value.initData(item,type); // 调用子组件方法
    //   }
    // });

  } else if (type == 'warrantyList') {
    resultData.value.warrantyList = item
    //   nextTick(() => {
    //   if (itemViewRef.value) {
    //     itemViewRef.value.initData(item,type); // 调用子组件方法
    //   }
    // });

  }

  drawer.value = true
}

function openAllocationDrawer() {
  allocationDrawer.value = true
  // 使用 nextTick 确保组件已经渲染
  nextTick(() => {
    if (allocationRef.value) {
      allocationRef.value.initData(form.value, "2", 'accountingComplete');
    } else {
      console.error("allocationRef is not available yet!");
    }
  });
}

const openRollBack = ref(false)

async function submitRollBack() {

  //1.删除当前环节信息 
  //2.更新上一个环节状态为进行中,去掉审核信息audit
  let updateParams = {
    projectNo: projectNo.value,
    id: currenrPhaseId.value,//当前环节的id
    backId: 6,//上一个环节的id
    remark: form.value.phaseRemark
  }
  const robackData = await rollBackPhase(updateParams).then((response) => {
    console.log("回退环节", response);
    return response
  });

  if (robackData.data) {
    openRollBack.value = false
    router.push({
      path: '/warranty/projectWarranty',
      query: { projectNo: projectNo.value }
    });
  }

}

function cancelRollBack() {
  openRollBack.value = false
}

function rollBack() {
  openRollBack.value = true

}

function openDrawerTime() {
  drawerTime.value = true
}



const { queryParams, form, personForm, payRules, warrantyRules, fileForm, warrantyForm, result, } = toRefs(data);


function getCurrUser(id) {
  getPosts(id).then(response => {
    console.log("66666666", response);
  });
}




//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)

  console.log("添加财务信息", finance.value);
}

async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}


function initData() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位信息", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

  getInfo().then((res) => {
    console.log("当前用户", res);
    getCurrUser(res.user.userId)
  })
    .catch((error) => {
      console.log("error", error);
    });
}


/** 查询绩效基本信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAcceptTime && "" != daterangeAcceptTime) {
    // queryParams.value.params["beginAcceptTime"] = daterangeAcceptTime.value[0];
    // queryParams.value.params["endAcceptTime"] = daterangeAcceptTime.value[1];
    queryParams.value.beginAcceptTime = daterangeAcceptTime.value[0];
    queryParams.value.endAcceptTime = daterangeAcceptTime.value[1];
  }
  listProject(queryParams.value).then((response) => {
    console.log("项目信息", response);
    projectList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
    console.log('projectList', projectList);

  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openView.value = false
  reset();
}

// 取消按钮
function cancelWarranty() {
  openWarranty.value = false;
  resetWarranty();
}

import mainList from "../mainList.vue";
import saleList from "../saleList.vue";
import feeList from "../fee.vue"
import compareMainAndSale from "../compareMainAndSale.vue"
import matching from "../matching.vue"
const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}


// 表单重置
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null
  };
  proxy.resetForm("projectRef");
}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置按钮操作 */
function resetQuery() {
  daterangeAcceptTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.minProjectAmount = null
  queryParams.value.maxProjectAmount = null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.projectNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}



/** 添加立项前期信息 */
async function handleUpdate(row) {
  activeName.value = "first"
  reset();
  const _projectNo = row.projectNo || ids.value;
  projectNo.value = row.projectNo //存放项目id
  isSale()
  contractAmount.value = row.contractAmount
  settlementAmount.value = row.settlementAmount
  company.value = row.housekeeperName
  companyId.value = row.housekeeperProject
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    isView.value = false
    title.value = "修改项目基本信息";
  });

  // getListParticipan(row.projectNo)
  getCurrPhase(projectNo.value)
  await getResults(row.projectNo).then((response) => {
    nextTick(() => {
      console.log("xxxxxxx", response);
      resultData.value = { ...response.data }
      console.log("统计信息", resultData.value);
      open.value = true;
    });
  });
}


function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }



  getResults(projectNo).then((response) => {
    console.log("xxxxxxx", response);
    resultData.value = { ...response.data }
    console.log("统计信息", resultData.value);
  });

  //参与人
  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data
  });

  //附件
  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });

  //付款信息
  listPay(params).then((response) => {
    payList.value = response.data;
  });

  //核算信息
  listAccounting(params).then((response) => {
    accountingList.value = response.data;
  });

  //质保信息
  listWarranty(params).then((response) => {
    warrantyList.value = response.data;
  });

  listImplement(params).then((response) => {
    implementList.value = response.data;
  });


  listPhase(params).then((response) => {
    logs.value = response.data.list;

  });



  isFinance()

  let currPhase = {
    projectNo: projectNo,
    phaseId: 1
  }



}


/** 阶段管理操作 */
async function handleView(row) {
  formDisabled.value = true
  isView.value = true
  reset();
  getListParticipan(row.projectNo)
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
  });

}



function nextPhase() {
  //判断财务收款金额跟结算金额能否对得上
  //判断质保期限是否到期 需要到期才可

  proxy.$modal.msgError("结算金额为20000 ,实收1800 不能进行归档");
  proxy.$modal.msgError("项目处于质保期内,不能归档");

  return
  //更新当前阶段为完成
  let updateParams = {
    id: currenrPhaseId.value,
    status: 2,//已完成
  }
  updatePhase(updateParams).then((response) => {
    proxy.$modal.msgSuccess("归档成功");
  });
  //插入下一个阶段的信息 状态进行中
  //项目归档6 字典值为6 写死
  // const filteredObjects = phase_type.value.filter((obj) => obj.value == 6);
  // personForm.value.phaseName = filteredObjects[0]?.label
  // personForm.value.phaseId = filteredObjects[0]?.value
  // let params = {
  //   projectNo: projectNo.value,
  //   phaseId: 6,//项目归档
  //   status: 1,//进行中
  //   phaseName: filteredObjects[0]?.label
  // }
  // addPhase(params).then((response) => {

  // });
  // proxy.$modal.msgSuccess("提交成功");
  status.value = 2
}



function getCurrPhase(projectNo) {
  let currPhase = {
    projectNo: projectNo,
    phaseId: 7//项目归档
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data == null) {
      //  currenrPhaseId.value = response.data.id
    } else {
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
    }
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/project/export",
    {
      ...queryParams.value,
    },
    `project_${new Date().getTime()}.xlsx`
  );
}

function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day}`;
};

getList();
initData()



loadUserColumnConfig()


// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },
]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);


  // 调用保存到后端的接口
  await saveUserTableConfig({ configs: selectedProps.value, type: "wait" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
    case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "wait" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}



async function isSale() {
  let params = {
    projectNo: projectNo.value,
    postIds: [5]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  isSales.value = res
}


import useUserStore from '@/store/modules/user'

const userStore = useUserStore()


</script>

<style scoped>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}

.el-col {
  text-align: center;
}


/* 移动端适配样式 */
.mobile-row .el-card {
  width: 100% !important;
  margin-bottom: 15px;
}

.mobile-row {
  margin-left: 0 !important;
}
</style>
